importgreenfoot.*;// (World, Actor, GreenfootImage, and Greenfoot)/**
* A hill full of ants.
*
* @author Michael Kolling
* @version 1.1
*/publicclass AntHill extends Actor
{/** Number of ants that have come out so far. */privateint ants =0;/** Total number of ants in this hill. */privateint maxAnts =40;/** Counter to show how much food have been collected so far. */private Counter foodCounter;/**
* Constructor for ant hill with default number of ants (40).
*/public AntHill(){}/**
* Construct an ant hill with a given number of ants.
*/public AntHill(int numberOfAnts){
maxAnts = numberOfAnts;}/**
* Act: If there are still ants left inside, see whether one should come out.
*/publicvoid act(){if(ants < maxAnts){if(Greenfoot.getRandomNumber(100)<10){
getWorld().addObject(new Ant(this), getX(), getY());
ants++;}}}/**
* Record that we have collected another bit of food.
*/publicvoid countFood(){if(foodCounter ==null){
foodCounter =new Counter("Food: ");int x = getX();int y = getY()+ getImage().getWidth()/2+8;
getWorld().addObject(foodCounter, x, y);}
foodCounter.increment();}}
importgreenfoot.*;// (World, Actor, GreenfootImage, and Greenfoot)/**
* Counter that displays some taxt and a number.
*
* @author Michael Kolling
* @version 1.1
*/publicclass Counter extends Actor
{privateint value = 0;privateString text;/**
* Create a counter without a text prefix, initialized to zero.
*/public Counter(){this("");}/**
* Create a counter with a given text prefix, initialized to zero.
*/public Counter(String prefix){
text = prefix;int imageWidth= (text.length() + 2)*10;
setImage(new GreenfootImage(imageWidth, 16));
updateImage();}/**
* Increment the counter value by one.
*/publicvoid increment(){
value++;
updateImage();}/**
* Show the current text and count on this actor's image.
*/privatevoid updateImage(){
GreenfootImage image = getImage();
image.clear();
image.drawString(text + value, 1, 12);}}
- 有限数量的蚂蚁;
- 巢穴的位置,可以由本身控制也可以从world对象控制;
- 巢穴的样子,就是图片的设置;
- 巢穴中蚂蚁找到的食物的数量
上面AntHill中提到一个Counter类,介绍一下他的实现:返回